﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Threading;
using TdxConnector.Messages;

namespace TdxConnector
{
    public class TdxService : ITdxService
    {
        public TdxService() 
        {
        }

        public int SendOrder(int category, string zqdm, double price, int quantity)
        {
            return QueueMessage(new SendOrderMessage()
                {
                    category = category,
                    price = price,
                    quantity = quantity,
                    zqdm = zqdm
                }).Result;
        }

        public bool CancelOrder(int nth)
        {
            return QueueMessage(new CancelOrderMessage(){nth = nth}).Result;
        }

        public Asset GetAsset()
        {
            return QueueMessage(new GetAssetMessage()).Result;
        }

        public Position[] GetPositions()
        {
            return QueueMessage(new GetPositionsMessage()).Result;
        }

        public Order[] GetOrders(bool excludeCancelled = true)
        {
            return QueueMessage(new GetOrdersMessage() { ExcludeCancelled = excludeCancelled }).Result;
        }

        private static T QueueMessage<T>(T m) where T : Message
        {
            MessageQueue.Instance.Enqueue(m);

            m.WaitHandle.WaitOne(5000);

            return m;
        }
    }
}
